<template>
  <div class="registration-info">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <van-icon name="arrow-left" size="20" @click="goBack" />
      <h2>{{ isEditMode ? '修改认证信息' : '预约认证' }}</h2>
      <div class="placeholder"></div>
    </div>
    
    <!-- 表单内容 -->
    <div class="form-container">
      <!-- 加载提示 -->
      <div v-if="loading" class="loading-hint">
        <van-loading size="24px" vertical>正在加载信息...</van-loading>
      </div>
      
      <!-- 表单 -->
      <van-form v-else @submit="onSubmit">
        <!-- 姓名字段 -->
        <div class="form-item">
          <van-field
            v-model="formData.name"
            name="name"
            label="姓名"
            placeholder="真实姓名"
            :rules="[{ required: true, message: '请输入姓名' }]"
            required
          />
        </div>
        
        <!-- 牌照号码字段 -->
        <div class="form-item">
          <van-field
            v-model="formData.plateNumber"
            name="plateNumber"
            label="牌照号码"
            placeholder=""
            :rules="[{ required: true, message: '请输入牌照号码' }]"
            required
          >
            <!-- <template #button>
              <div class="plate-upload">
                <van-icon name="scan" size="24" color="#ff8800" @click="handleScanPlate" />
              </div>
            </template> -->
          </van-field>
        </div>
        
        <!-- 身份证字段 -->
        <div class="form-item">
          <van-field
            v-model="formData.idCard"
            name="idCard"
            label="身份证"
            placeholder="15或18位身份证号码"
            :rules="[
              { required: true, message: '请输入身份证号码' },
              { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$|^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}$/, message: '请输入正确的身份证号码' }
            ]"
            required
          />
        </div>
        
        <!-- 电话号码字段 -->
        <div class="form-item">
          <van-field
            v-model="formData.phone"
            name="phone"
            label="电话号码"
            placeholder="电话号码"
            type="tel"
          />
        </div>
        
        <!-- 提交按钮 -->
        <div class="submit-section">
          <van-button 
            type="primary" 
            block 
            round
            native-type="submit"
            :loading="submitting"
            class="submit-btn"
          >
            {{ isEditMode ? '保存修改' : '提交' }}
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { showToast, showSuccessToast, showLoadingToast, closeToast } from 'vant'
import { useRouter } from 'vue-router'
import { getWechatOpenId } from "../store.js";

const router = useRouter()
const submitting = ref(false)
const loading = ref(false)
const isEditMode = ref(false) // 是否为编辑模式

// 获取全局API
const { proxy } = getCurrentInstance()
const $api = proxy.$api

// 表单数据
const formData = reactive({
  name: '',
  plateNumber: '',
  idCard: '',
  phone: ''
})

const fwid = getWechatOpenId();

// 查询注册信息
const fetchRegisterInfo = async () => {
  if (!fwid) {
    showToast('未获取到微信ID，请先从首页授权')
    setTimeout(() => {
      router.push('/')
    }, 2000)
    return
  }

  try {
    loading.value = true
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    })

    console.log('查询注册信息，fwid:', fwid)

    const response = await $api.getRegisterInfo(fwid)

    console.log('注册信息查询结果:', response)

    closeToast()

    if (response && response.code === 200) {
      if (response.data && response.data.realName) {
        // 有数据，填充表单，进入编辑模式
        formData.name = response.data.realName || ''
        formData.idCard = response.data.idCard || ''
        formData.plateNumber = response.data.licensePlate || ''
        formData.phone = response.data.phone || ''
        isEditMode.value = true
        console.log('已有注册信息，进入编辑模式')
      } else {
        // 无数据，进入注册模式
        isEditMode.value = false
        console.log('无注册信息，进入注册模式')
      }
    } else {
      console.warn('查询注册信息失败:', response?.msg)
      // 查询失败也可以注册
      isEditMode.value = false
    }
  } catch (error) {
    closeToast()
    console.error('查询注册信息出错:', error)
    // 错误也可以继续注册
    isEditMode.value = false
  } finally {
    loading.value = false
  }
}

// 页面加载时查询
onMounted(() => {
  fetchRegisterInfo()
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 扫描车牌
// const handleScanPlate = () => {
//   showToast('扫描车牌功能')
// }

// 表单提交
const onSubmit = async (values) => {
  try {
    submitting.value = true
    
    // 构建请求参数
    const registrationInfo = {
      fwid: fwid,
      realName: values.name,
      idCard: values.idCard,
      licensePlate: values.plateNumber,
      phone: values.phone
    }
    
    console.log(isEditMode.value ? '提交修改信息:' : '提交注册信息:', registrationInfo)
    
    // 调用API提交注册信息（注册和修改都是同一个接口）
    const result = await $api.registerAppointment(registrationInfo)
    
    if (result.code === 200) {
      if (isEditMode.value) {
        showSuccessToast(result.msg || '信息修改成功')
      } else {
        showSuccessToast(result.msg || '认证信息提交成功')
      }
      
      // 提交成功后返回上一页
      setTimeout(() => {
        router.back()
      }, 1000)
    } else {
      showToast(result.msg || '提交失败，请重试')
    }
    
  } catch (error) {
    console.error('注册信息提交错误:', error)
    showToast(error.message || '提交失败，请重试')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
/* 全局样式优化 */
.registration-info {
  background: linear-gradient(180deg, #f8faff 0%, #f0f4ff 100%);
  min-height: 100vh;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 16px 12px 16px;
  background: linear-gradient(135deg, #f8f9ff 0%, #e8f4f8 100%);
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  position: relative;
  flex-shrink: 0;
}

.nav-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 0 0;
  letter-spacing: 0.5px;
  flex: 1;
  text-align: center;
}

.nav-header .van-icon {
  color: #2c3e50;
  cursor: pointer;
  padding: 4px;
  transition: all 0.3s ease;
}

.nav-header .van-icon:hover {
  color: #667eea;
}

.placeholder {
  width: 28px;
  height: 28px;
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding: 20px 16px;
}

/* 加载提示 */
.loading-hint {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  color: #667eea;
}

/* 表单项样式 */
.form-item {
  margin: 0 0 16px 0;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(102, 126, 234, 0.08);
}

.form-item .van-field {
  background: white;
  border-radius: 12px;
}

.form-item .van-field__label {
  color: #2c3e50;
  font-weight: 600;
  font-size: 15px;
  width: 80px;
  margin: 0 12px 0 0;
}

.form-item .van-field__control {
  color: #2c3e50;
  font-size: 15px;
}

.form-item .van-field__control::placeholder {
  color: #c8c9cc;
  font-size: 14px;
}

/* 车牌扫描按钮 */
.plate-upload {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: rgba(255, 136, 0, 0.1);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0 8px 0 0;
}

.plate-upload:hover {
  background: rgba(255, 136, 0, 0.15);
  transform: scale(1.05);
}

.plate-upload:active {
  transform: scale(0.95);
}

/* 提交按钮区域 */
.submit-section {
  margin: 40px 0 20px 0;
}

.submit-btn {
  background: linear-gradient(135deg, #4A90E2, #357ABD);
  border: none;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 1px;
  box-shadow: 0 4px 16px rgba(74, 144, 226, 0.3);
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(74, 144, 226, 0.4);
}

.submit-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(74, 144, 226, 0.3);
}

.submit-btn.van-button--loading {
  background: linear-gradient(135deg, #8bb4e8, #6a9bd1);
}

/* 必填标识样式 */
.van-field__label::after {
  content: '*';
  color: #ee0a24;
  margin: 0 0 0 2px;
}

/* 错误状态样式 */
.van-field--error .van-field__control {
  color: #ee0a24;
}

.van-field--error {
  border-color: rgba(238, 10, 36, 0.3);
  background: rgba(238, 10, 36, 0.02);
}

/* 响应式优化 */
@media screen and (max-width: 375px) {
  .nav-header h2 {
    font-size: 16px;
  }
  
  .form-container {
    padding: 16px 12px;
  }
  
  .form-item .van-field__label {
    font-size: 14px;
    width: 70px;
  }
  
  .form-item .van-field__control {
    font-size: 14px;
  }
  
  .submit-btn {
    height: 44px;
    font-size: 15px;
  }
}

/* 加载动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-item {
  animation: fadeInUp 0.4s ease forwards;
}

.form-item:nth-child(1) { animation-delay: 0.1s; }
.form-item:nth-child(2) { animation-delay: 0.2s; }
.form-item:nth-child(3) { animation-delay: 0.3s; }
.form-item:nth-child(4) { animation-delay: 0.4s; }

.submit-section {
  animation: fadeInUp 0.6s ease 0.5s forwards;
}

/* 聚焦状态优化 */
.van-field--focus {
  border-color: rgba(102, 126, 234, 0.3);
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

/* 输入框内边距调整 */
.van-field__control {
  padding: 0 0 0 0;
}

.van-field__body {
  padding: 16px 16px;
}
</style>